#pragma once
#define LOG_LEVEL 3

#include <vector>
#include "RTMPlayer.cpp"
#include "TCPlayer.cpp"
#include "PlayerManager.cpp"

std::shared_ptr<PlayerManager> playerManager{};

//RTMP
extern "C"
JNIEXPORT void JNICALL
Java_com_steam_video_Player_createRTMP(JNIEnv *env, jclass type, jobject surface, jstring address1_,
                                       jstring address2_, jobject listener) {
    releaseGlobal(env);
    env->GetJavaVM(&gPVm);
    gPListener = env->NewGlobalRef(listener);
    gPSurface = env->NewGlobalRef(surface);
    std::vector<std::shared_ptr<PlayerBase>> players{
            std::make_shared<RTMPlayer>(getCharFormJava(env, address1_)),
            std::make_shared<RTMPlayer>(getCharFormJava(env, address2_))
    };
    playerManager = std::make_shared<PlayerManager>(std::move(players));
}

//TCP
extern "C"
JNIEXPORT void JNICALL
Java_com_steam_video_Player_createTCP(JNIEnv *env, jclass type, jobject surface, jstring address1_,
                                     jstring address2_, jint port1, jint port2, jobject listener) {
    releaseGlobal(env);
    env->GetJavaVM(&gPVm);
    gPListener = env->NewGlobalRef(listener);
    gPSurface = env->NewGlobalRef(surface);
    std::vector<std::shared_ptr<PlayerBase>> players{
            std::make_shared<TCPlayer>(ServerInfo{getCharFormJava(env, address1_),port1}),
            std::make_shared<TCPlayer>(ServerInfo{getCharFormJava(env, address2_),port2})
    };
    playerManager = std::make_shared<PlayerManager>(std::move(players));
}

extern "C"
JNIEXPORT void JNICALL
Java_com_steam_video_Player_startPlay(JNIEnv *env, jclass type) {
    if (playerManager.get() != nullptr) playerManager->resume();
}

extern "C"
JNIEXPORT void JNICALL
Java_com_steam_video_Player_stopPlay(JNIEnv *env, jclass type) {
    if (playerManager.get() != nullptr) playerManager->pause();
}

extern "C"
JNIEXPORT void JNICALL
Java_com_steam_video_Player_destroy(JNIEnv *env, jclass type) {
    if (playerManager.get() != nullptr) playerManager.reset();
    releaseGlobal(env);
}

extern "C"
JNIEXPORT void JNICALL
Java_com_steam_video_Player_switchSteam(JNIEnv *env, jclass type) {
    if (playerManager.get() != nullptr) playerManager->switchSteam();
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_steam_video_Player_activeIndexSteam(JNIEnv *env, jclass type) {
    if (playerManager.get() != nullptr) return playerManager.get()->activeIndex();
    else return -1;
}
